package org.xmls.common.base.response;

import lombok.*;
import lombok.experimental.Accessors;
import lombok.experimental.FieldNameConstants;
import org.xmls.common.base.exception.enums.GlobalErrCodeEnum;

import java.io.Serializable;
import java.util.UUID;

/**
 * 响应信息主体
 *
 * @param <T>
 */
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@FieldNameConstants
@Data
public class R<T> implements Serializable {

	private String request_id;

	private int code;

	private String msg;

	private T data;

	public static <T> R<T> ok() {
		return restResult(null, GlobalErrCodeEnum.SUCCESS.getCode(), null);
	}

	public static <T> R<T> ok(T data) {
		return restResult(data, GlobalErrCodeEnum.SUCCESS.getCode(), null);
	}

	public static <T> R<T> ok(T data, String msg) {
		return restResult(data, GlobalErrCodeEnum.SUCCESS.getCode(), msg);
	}

	public static <T> R<T> failed() {
		return restResult(null, GlobalErrCodeEnum.COMMON_ERROR.getCode(), null);
	}

	public static <T> R<T> failed(int code) {
		return restResult(null, code, null);
	}

	public static <T> R<T> failed(String msg) {
		return restResult(null, GlobalErrCodeEnum.COMMON_ERROR.getCode(), msg);
	}

	public static <T> R<T> failed(T data) {
		return restResult(data, GlobalErrCodeEnum.COMMON_ERROR.getCode(), null);
	}

	public static <T> R<T> failed(T data, int code, String msg) {
		return restResult(data, code, msg);
	}

	public static <T> R<T> restResult(T data, int code, String msg) {
		R<T> apiResult = new R<>();
		apiResult.setCode(code);
		apiResult.setData(data);
		if (msg == null) {
			msg = GlobalErrCodeEnum.getMessage(code);
		}
		apiResult.setMsg(msg);
		apiResult.setRequest_id(UUID.randomUUID().toString().replace("-", ""));
		return apiResult;
	}

}
